package cn.dgut.training.controller;

import cn.dgut.training.annotation.LoginUser;
import cn.dgut.training.dto.activity.CouponDTO;
import cn.dgut.training.dto.activity.CouponListDTO;
import cn.dgut.training.dto.activity.CouponUserDTO;
import cn.dgut.training.entity.activity.Coupon;
import cn.dgut.training.entity.activity.CouponUser;
import cn.dgut.training.service.impl.CouponServiceImpl;
import cn.dgut.training.service.impl.CouponUserServiceImpl;
import cn.dgut.training.vo.BaseVO;
import cn.dgut.training.vo.CommonResponse;
import cn.dgut.training.vo.activity.CouponVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/coupon")
@Slf4j
public class CouponController {

    @Resource
    private CouponServiceImpl couponService;

    @Resource
    private CouponUserServiceImpl couponUserService;



    /**
     * 添加
     * @param coupon
     * @return
     */
    @PostMapping("/create")
    public CommonResponse add(@RequestBody Coupon coupon){
        return couponService.add(coupon);
    }

    /**
     * 查询分页接口辑删除字段为0的优惠券
     * @param couponDTO
     * @return
     */
    @PostMapping("/list")
    public CommonResponse listCouponByPage(@RequestBody CouponDTO couponDTO){
        return CommonResponse.success(couponService.listCouponByPage(couponDTO));
    }


    /**
     * 编辑
     * @param coupon
     * @return
     */
    @PutMapping
    public CommonResponse edit(@RequestBody Coupon coupon){
        couponService.updateById(coupon);
        return CommonResponse.success(coupon);
    }

    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public CommonResponse getById(@PathVariable("id") long id){

        return CommonResponse.success(couponService.getById(id));


    }

    /**
     * 根据id更新逻辑删除字段为1
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public CommonResponse deleteById(@PathVariable("id") long id){

        couponService.removeById(id);
        return CommonResponse.message();
    }



    /**
     * 获取两条记录
     * @return
     */
    @GetMapping("/two")
    public List getTwo(){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("coupon_type",0);
        queryWrapper.last("limit 2");

        List<Coupon> couponList=couponService.list(queryWrapper);
        List<CouponVO> res=new ArrayList<>();
        for (Coupon c:couponList) {
            CouponVO couponVO=new CouponVO();
            BeanUtils.copyProperties(c,couponVO);
            res.add(couponVO);
        }

        return res;
    }


    /**
     * 领取优惠券
     * @param userId
     * @param couponJson
     * @return
     */
    @PostMapping("/receive")
    @Transactional
    public CommonResponse receive(@LoginUser Long userId, @RequestBody String couponJson){


        //1.判断优惠券是否领完
        JSONObject jsonObject = JSONObject.parseObject(couponJson);
        long couponId=Long.parseLong(jsonObject.getString("couponId"));

        Coupon coupon=couponService.getById(couponId);
        Integer total=coupon.getTotal();
        if(total<=0){
            return CommonResponse.fail("优惠券已领完");
        }

        //2.判断优惠券是否领过：不是无限量并且超过领取数量
        Integer couponLimit=coupon.getCouponLimit();
        Integer count=couponUserService.countUserAndCoupon(userId,couponId);
        if(couponLimit!=0&&count>=couponLimit){
            return CommonResponse.fail("优惠券已经领过");
        }

        //3.存储用户和优惠券的关系
        couponUserService.saveCouponUser(userId,couponId);
        coupon.setTotal(coupon.getTotal()-1);
        couponService.updateById(coupon);

        return CommonResponse.message();

    }

    /**
     * 后台：根据优惠券id，分页查询当前优惠券被哪些用户领取
     * @param couponUserDTO
     * @return
     */
    @PostMapping("/listuser")
    public CommonResponse listUserCoupon(@RequestBody CouponUserDTO couponUserDTO){

        return CommonResponse.success(couponUserService.listCouponUserByPage(couponUserDTO));

    }


    /**
     * 下单：当前订单可用优惠券
     */
    @RequestMapping("/selectlist")
    public CommonResponse selectCouponsByOrder(@LoginUser Long userId,Long cartId, Long grouponRulesId){

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", couponService.selectCouponsByOrder(userId,cartId,grouponRulesId));
        return CommonResponse.success(data);
    }


    /**
     * 通过状态分页查询当前用户的优惠券，默认为未使用
     * @return
     */
    @PostMapping("/mylist")
    public CommonResponse getCouponsByUserId(@LoginUser Long userId,@RequestBody CouponListDTO couponListDTO){

        BaseVO baseVO=couponUserService.selectCurrentCoupons(userId,couponListDTO);

        return CommonResponse.success(baseVO);
    }

    /**
     * 输入兑换码兑换优惠券
     * @return
     */
    @PostMapping("/exchange")
    public CommonResponse code(@LoginUser Long userId,@RequestBody  Map<String,String> map){

        Coupon coupon=couponService.getCoupunByCode(map.get("code"));

        if(coupon==null){
            return CommonResponse.fail("兑换失败");
        }
        couponUserService.saveCouponUser(userId,coupon.getId());

        return CommonResponse.message();
    }

    /**
     * 返回优惠券实体给订单模块
     * @param userId
     * @param couponId
     * @return
     */
    @PostMapping("/ordersUse")
    public Coupon orderUse(@RequestParam("userId") Long userId,@RequestParam("couponId")Long couponId){
        if(couponUserService.list(new QueryWrapper<CouponUser>().lambda()
                .eq(CouponUser::getCouponId,couponId).eq(CouponUser::getUserId,userId)).size()==0){
            return null;
        }
        else {
            return couponService.getById(couponId);
        }
    }

    /**
     * 通过couponUserId得到couponUser
     * @param couponUserId
     * @return
     */
    @PostMapping("/getUserCoupon")
    public CouponUser getUserCoupon(@RequestParam("couponUserId") Long couponUserId){
        return couponUserService.getOne(new LambdaQueryWrapper<CouponUser>().eq(CouponUser::getCouponId,couponUserId));
    }


    @GetMapping("/useUserCoupon")
    public void useUserCoupon(@RequestParam("couponId") Long  couponId,@RequestParam("orderId") Long  orderId){

        CouponUser couponUser = couponUserService.getOne(new LambdaQueryWrapper<CouponUser>()
        .eq(CouponUser::getCouponId,couponId));
        couponUser.setStatus(1);
        couponUser.setUsedTime(new Date());
        couponUser.setOrderId(orderId);
        couponUserService.updateById(couponUser);
    }

    @PostMapping("/listAllByUser")
    public List<CouponUser> listAllByUser(@RequestParam("userId") Long userId){
        return couponUserService.list(new QueryWrapper<CouponUser>().lambda().eq(CouponUser::getUserId,userId)
                .eq(CouponUser::getStatus,0));
    }

    @PostMapping("/accordWith")
    public Coupon accordWith(@RequestParam("couponId") Long couponId,@RequestParam("price") BigDecimal price){
        return couponService.getOne(new QueryWrapper<Coupon>().lambda().eq(Coupon::getId,couponId).le(Coupon::getCouponMin,price));
    }



}
